// Kruskal
// https://www.luogu.com.cn/problem/P1340

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;

const int maxn = 5 + 1e3;

// disjoint-set
int f[maxn], fsiz;
int find(int x) {
    if (f[x] == x) return x;
    return f[x] = find(f[x]);
}
void merge(int l, int r) { f[find(l)] = find(r); };

// Graph
int n, m;
using Edg = pair<int, pair<int, int>>;  // <w, l, r>
vector<Edg> edg;

int Kruskal() {
    int remain_cnt = n, sum = 0;  // 生成树还差多少个节点，生成树边权和
    sort(edg.begin(), edg.end());
    for (int i = 1; i <= n; ++i) f[i] = i;  // init dj-set

    for (auto &p : edg) {
        int l = p.second.first, r = p.second.second, w = p.first;
        if (find(l) != find(r)) {
            merge(l, r);
            sum += w;
            --remain_cnt;
        }
        if (remain_cnt == 1) break;
    }
    return remain_cnt == 1 ? sum : -1;
}

// int main() {
//     int sum = 0;
//     cin >> n >> m;
//     for (int i = 1; i <= m; ++i) {
//         int l, r, w;
//         cin >> l >> r >> w;
//         edg.push_back({w, {l, r}});
//         cout << Kruskal() << endl;
//     }
// }
